package org.rollinitiative.d20web.charactersheet.client;

import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.DockPanel;
import com.google.gwt.user.client.ui.FlowPanel;
import com.google.gwt.user.client.ui.ListBox;
import com.google.gwt.user.client.ui.RootPanel;

/**
 * Entry point classes define <code>onModuleLoad()</code>.
 */
public class CharacterSheetApplication implements EntryPoint {

	private CharacterView characterView;
	private DockPanel mainPanel;
	private final CharacterServiceAsync characterService = GWT.create(CharacterService.class);
	private ListBox characterList;

	String defaultCampaign = "arena";

	/**
	 * This is the entry point method.
	 */
	public void onModuleLoad() {

		// Issue RPC query for characters
		characterService.getParty(defaultCampaign, charactersCallback);
	}

	AsyncCallback<String[]> charactersCallback = new AsyncCallback<String[]>() {
		public void onSuccess(String[] result) {
			initView(result);
		}

		public void onFailure(Throwable caught) {
			GWT.log("Call for character list retrieval failed", caught);
		}
	};

	private void initView(String[] characters) {
		mainPanel = new DockPanel();
		characterList = new ListBox();
		FlowPanel selectPanel = new FlowPanel();
		characterList.setVisibleItemCount(1);
		for (int i = 0; i < characters.length; i++) {
			characterList.addItem(characters[i]);

		}
		selectPanel.add(characterList);
		final Button button = new Button("Load Selection");
		selectPanel.add(button);

		button.addClickHandler(new ClickHandler() {
			public void onClick(ClickEvent sender) {
				load();
			}
		});

		mainPanel.add(selectPanel, DockPanel.NORTH);
		
		characterView = new CharacterView();
		mainPanel.add(characterView, DockPanel.CENTER);
		mainPanel.setSize("100%", "100%");

		RootPanel.get().add(mainPanel);
	}

	private void load() {
		// Create an asynchronous callback to handle the result.
		AsyncCallback<CharacterData> callback = new AsyncCallback<CharacterData>() {
			public void onSuccess(CharacterData result) {
				characterView.setCharacter(result);
			}

			public void onFailure(Throwable caught) {
				GWT.log("Call for character retrieval failed", caught);
			}
		};

		// Make the call. Control flow will continue immediately and later
		// 'callback' will be invoked when the RPC completes.
		int selection = characterList.getSelectedIndex();
		characterService.getCharacter(characterList.getValue(selection),
				callback);
	}

//	private void setCharacter(CharacterData character) {
//		characterView_.setCharacter(character);
//		mainPanel_.add(characterView_, DockPanel.CENTER);
//		mainPanel_.setSize("100%", "100%");
//	}

}
